// 2025/11/11
// 删除链表的倒数第N个结点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        stack<ListNode*> st;
        ListNode phead(0, head), *cur = &phead;
        while(cur)
        {
            st.emplace(cur);
            cur = cur->next;
        }
        ListNode* next = nullptr, *del;
        while(n--)
        {
            del = st.top(); st.pop();
            if(n == 1) next = del;
        }
        st.top()->next = next;
        delete del;
        return phead.next;
    }
};